<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>元素拖拽</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: #000;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div></div>
</body>
<script>
    function getStyle(elem, prop) {
        if (window.getComputedStyle) {
            return window.getComputedStyle(elem, null)[prop];
        }else{
            return elem.currentStyle[prop];
        }
    }

    function addEvent(elem, type, handle) {
        if (elem.addEventListener) {
            elem.addEventListener(type, handle, false);
        }else if(elem.attachEvent) {
            elem.attachEvent('on' + type, handle);
        }else{
            elem['on' + type] = handle;
        }
    }

    function removeEvent(elem, type, handle) {
        if (elem.removeEventListener) {
            elem.removeEventListener(type, handle, false);
        }else{
            elem.attachEvent('on' + type, handle);
        }
    }

    function stopBubble(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        }else{
            event.cancelBubble();
        }
    }

    function cancelHandler(event) {
        if (event.preventDefault) {
            event.preventDefault();
        }else{
            event.returnValue = false;
        }
    }

    /**
     * 拖拽元素
     * @Author   hflxhn.com
     * @DateTime 2019-11-03T18:06:11+0800
     * @param    {obj}                 elem [要拖拽元素]
     */
    function drag(elem) {
        var dis_x,
            dis_y;
        addEvent(elem, 'mousedown', function(e) {
            var event = e || window.event;
            dis_x = event.clientX - parseInt(getStyle(elem, 'left'));
            dis_y = event.clientY - parseInt(getStyle(elem, 'top'));
            addEvent(document, 'mousemove', mouseMove);
            addEvent(document, 'mouseup', mouseUp);
            stopBubble(event);
            cancelHandler(event);
        });
        function mouseMove(e) {
            var event = e || window.event;
            elem.style.left = event.clientX - dis_x + 'px';
            elem.style.top = event.clientY - dis_y + 'px';
        }
        function mouseUp(e) {
            var event = e || window.event;
            removeEvent(document, 'mousemove', mouseMove);
            removeEvent(document, 'mouseup', mouseUp);
        }
    }

    var div = document.getElementsByTagName('div')[0];
    drag(div);
</script>
</html>
